//
//  THHomeViewController.m
//  TreeHole
//
//  Created by apple on 2020/7/27.
//  Copyright © 2020 stoneobs. All rights reserved.
//

#import "THHomeViewController.h"
#import "THBaseTableView.h"
#import "THHomeSegeViewController.h"
#import "THChildSelectViewController.h"
#import "THSubCateViewController.h"
#import "STTools_QRCodeCodeController.h"
#import "BSPayResultViewController.h"
@interface THHomeViewController ()<UITableViewDelegate>
@property(nonatomic, strong) UITableView                     *tableView;/**<  */
@property(nonatomic, strong) THHomeSegeViewController                     *seg_vc;/**<  */
@property(nonatomic, strong) STTools_SegementAutoView                     *segView;/**<  */

@property(nonatomic, strong) UIView                     *seg_contentview;/**<  */
@property(nonatomic, strong) THHomeModel                     *homeModel;/**<  */
@property(nonatomic, strong) UIView                     *mineLoadingView;/**<  */
@end

@implementation THHomeViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBar.hidden = YES;
    __weak typeof(self) weakSelf =  self;
    self.mineLoadingView = [[STTools_NoresultView alloc] initWithFrame:CGRectMake(0, self.tableView.tableHeaderView.height + 30, STONEOBS_UI_UISCREEN_WIDTH, 400) title:@"正在加载" buttonTitle:@"" buttonHandle:^(NSString *titleString) {
        
    }];
    [self.view addSubview:self.mineLoadingView];
    
    [THHomeDataController stoneobs_fun_get_home_model:^(THHomeModel * _Nonnull model) {
        if (!self.homeModel) {
            self.homeModel = model;
        }
    }];

    // Do any additional setup after loading the view.
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [THHomeDataController stoneobs_fun_get_home_model:^(THHomeModel * _Nonnull model) {
        if (!self.homeModel) {
            self.homeModel = model;
        }
    }];
}
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
}
- (void)setHomeModel:(THHomeModel *)homeModel{
    _homeModel = homeModel;
    [self.view removeAllSubviews];
    [self stoneobs_ui_configBaseView];
    [self stoneobs_ui_config_header_view];
    [self stoneobs_ui_config_footer_view];
}
#pragma mark --configSubView
- (void)config_load_view{
    
}
- (void)stoneobs_ui_configBaseView{
    self.navigationController.navigationBar.hidden = YES;
    __weak typeof(self) weakSelf =  self;
    ({
        STButton * stoneobs_ui_button = [[STButton alloc] initWithFrame:CGRectMake(0, 0, 74, 44)
                                                                  title:@"首页"
                                                             titleColor:UIColor.whiteColor
                                                              titleFont:20
                                                           cornerRadius:0
                                                        backgroundColor:nil
                                                        backgroundImage:nil
                                                                  image:nil];
        [self.view addSubview:stoneobs_ui_button];
        stoneobs_ui_button.bottom = TMUtils.stoneobs_fun_get_navgationBarBootom;
        [stoneobs_ui_button setClicAction:^(UIButton *sender) {
            
        }];
        stoneobs_ui_button.titleLabel.font = [UIFont fontWithName:STONEOBS_UI_FONT_CU_NAME size:20];
        stoneobs_ui_button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    });
    
    ({
        __weak typeof(self) weakSelf =  self;
        STButton * stoneobs_ui_button = [[STButton alloc] initWithFrame:CGRectMake(0, 0, 74, 33)
                                                                  title:@""
                                                             titleColor:UIColor.whiteColor
                                                              titleFont:20
                                                           cornerRadius:0
                                                        backgroundColor:nil
                                                        backgroundImage:nil
                                                                  image:ST_IMAGE_NAMED(@"扫一扫")];
        [self.view addSubview:stoneobs_ui_button];
        stoneobs_ui_button.centerY = TMUtils.stoneobs_fun_get_navgationBarBootom - 22;
        [stoneobs_ui_button setClicAction:^(UIButton *sender) {
            STTools_QRCodeCodeController * vc = [[STTools_QRCodeCodeController alloc] initWithHandle:^(NSString *result, STTools_QRCodeCodeController *vc) {
                [weakSelf.navigationController popViewControllerAnimated:YES];
                if ([result containsString:@"custom=/"]) {
                    [weakSelf stoneobs_fun_st_showAlertTitle:@"请您确认是否为您所要购买的产品" message:@"" leftTitle:@"是" rightTitle:@"否" block:^(NSString *name) {
                        if ([name isEqualToString:@"是"]) {
                            NSArray * array = [result componentsSeparatedByString:@"custom=/"];
                            BSPayResultViewController * vc = BSPayResultViewController.new;
                            vc.url = array.lastObject;
                            [weakSelf pushViewController:vc animated:1];
                        }
                    }];

                }else{
                    [UIApplication.sharedApplication openURL:result.mj_url options:nil completionHandler:^(BOOL success) {
                        
                    }];
                }
            }];
            [weakSelf pushViewController:vc animated:1];
        }];
        stoneobs_ui_button.right = UISCREEN_WIDTH;
        stoneobs_ui_button.titleLabel.font = [UIFont fontWithName:STONEOBS_UI_FONT_CU_NAME size:20];
        stoneobs_ui_button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    });
    
    ({
        CGFloat left = 74;
        CGFloat right = 74;
        
        STButton * stoneobs_ui_button = [[STButton alloc] initWithFrame:CGRectMake(left, 0, STONEOBS_UI_UISCREEN_WIDTH - left -right, 36)
                                                                  title:@"搜索"
                                                             titleColor:nil
                                                              titleFont:13
                                                           cornerRadius:18
                                                        backgroundColor:[UIColor.whiteColor colorWithAlphaComponent:0.55]
                                                        backgroundImage:nil
                                                                  image:ST_IMAGE_NAMED(@"搜索")];
        [self.view addSubview:stoneobs_ui_button];
        stoneobs_ui_button.contentEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);
        stoneobs_ui_button.titleEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);
        stoneobs_ui_button.centerY = TMUtils.stoneobs_fun_get_navgationBarBootom - 22;
        [stoneobs_ui_button setClicAction:^(UIButton *sender) {
            //去搜索
            [TMUtils goto_search_controller];
        }];
        
    });
    
    UIImageView * stoneobs_ui_imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, STONEOBS_UI_UISCREEN_WIDTH, 300)];
//    stoneobs_ui_imageView.image = [UIImage imageNamed:@"椭圆71"];
    stoneobs_ui_imageView.backgroundColor = [UIColor colorWithGradientStyle:UIGradientStyleTopToBottom withFrame:stoneobs_ui_imageView.bounds andColors:@[WH_UICOLOR_FROM_RGBA(0x4AD941),WH_UICOLOR_FROM_RGBA(0x37CF34),UIColor.whiteColor]];
    [self.view insertSubview:stoneobs_ui_imageView atIndex:0];
    
    self.tableView = [[THBaseTableView alloc] initWithFrame:STONEOBS_UI_UISCREEN_FRAME style:UITableViewStyleGrouped];
    self.tableView.backgroundColor = UIColor.clearColor;
    self.tableView.contentInset = UIEdgeInsetsZero;
    self.tableView.frame = CGRectMake(0, TMUtils.stoneobs_fun_get_navgationBarBootom, STONEOBS_UI_UISCREEN_WIDTH, TMUtils.stoneobs_fun_get_tabBarTop - TMUtils.stoneobs_fun_get_navgationBarBootom);
    [self.view addSubview:self.tableView];
    self.tableView.delegate = self;
    self.tableView.bounces = NO;
}
- (void)stoneobs_ui_config_header_view{
    
    
    UIView * header = [UIView.alloc initWithFrame:STONEOBS_UI_UISCREEN_FRAME];
    __weak typeof(self) weakSelf =  self;
    
    STTools_PageView * page_view = [[STTools_PageView alloc] initWithFrame:CGRectMake(10, 10, STONEOBS_UI_UISCREEN_WIDTH - 20, 160)];
//    page_view.imageArray = @[STFDRandomImageProvider.random_banner_shop_image,
//                             STFDRandomImageProvider.random_banner_shop_image,
//                             STFDRandomImageProvider.random_banner_shop_image,
//                             STFDRandomImageProvider.random_banner_shop_image
//    ].mutableCopy;
    page_view.imageUrlArray = [[self.homeModel.banner stoneobs_fun_arrayFromObjKeyName:@"obj.img"] mutableCopy];
    page_view.animationType = FSPagerViewTransformerTypeNone;
    [page_view setOnSelectedBannerHandle:^(NSInteger index) {
        
        THBannerModel * model = weakSelf.homeModel.banner[index];
        [TMUtils auto_deal_banner:model];
    }];
    page_view.backgroundColor = UIColor.clearColor;
    [header addSubview:page_view];
    page_view.pagerView.layer.cornerRadius = 4;
    page_view.pagerView.clipsToBounds = YES;
    page_view.autoMoveDuring = 4;
    
    STPageControl * pageControl = [STPageControl.alloc initWithPages:page_view.imageUrlArray.count handle:^(NSInteger tag) {
        
    }];
    pageControl.currentPageIndicatorTintColor  = STONEOBS_UI_THEME_BACKGROUNDCOLOR;
    pageControl.pageIndicatorTintColor = [STONEOBS_UI_THEME_BACKGROUNDCOLOR colorWithAlphaComponent:0.3];
    pageControl.centerX = STONEOBS_UI_UISCREEN_WIDTH / 2;
    pageControl.bottom = page_view.bottom - 35;
    [header addSubview:pageControl];
    __weak typeof(pageControl) weakpageControl=  pageControl;
    [page_view setScrollDidScroll:^(NSInteger currentIndex) {
        weakpageControl.currentPage = currentIndex;
    }];
    
    
    CGFloat top = page_view.bottom -20;
    
    ({
        UIView * white_view = [[UIView alloc] initWithFrame:CGRectMake(10, top, STONEOBS_UI_UISCREEN_WIDTH - 20, 200)];
        white_view.backgroundColor = UIColor.whiteColor;
        white_view.layer.cornerRadius = 0;
        white_view.clipsToBounds = YES;
        [header addSubview:white_view];
        
        NSArray * array = @[@{@"title":@"新品区",@"imageName":@"QQ"},
                            @{@"title":@"婴童",@"imageName":@"微信"},
                            @{@"title":@"玩具区",@"imageName":@"朋友圈"},
                            @{@"title":@"文具区",@"imageName":@"微博"},
                            @{@"title":@"精品区",@"imageName":@"QQ"},
                            @{@"title":@"快乐办公",@"imageName":@"微信"},
                            @{@"title":@"秒杀星期六",@"imageName":@"朋友圈"},
                            @{@"title":@"身边育婴师",@"imageName":@"微博"}
        ];
        array = self.homeModel.cates;
        CGFloat buttonWith = white_view.width / 4;
        for (NSInteger i = 0; i < array.count; i ++) {
//            NSDictionary * dic = array[i];
//            NSString * title= [dic[@"title"] description];
            THCateModel * model = array[i];
            NSString * title = model.name;
            STTools_MenuControl * menuControl = [[STTools_MenuControl alloc] initWithFrame:CGRectMake(0, 0, buttonWith, 100) imageName:model.local_icon_name title:title titleColor:STONEOBS_UI_FIRST_TEXT_COLOR];
            [menuControl setOnSelctedControl:^(STTools_MenuControl *control) {
                [weakSelf stoneobs_action_onselcted_menu_title:title model:model];
            }];
            menuControl.tag = 10000 + i;
            [white_view addSubview:menuControl];
            menuControl.left = (i % 4) * buttonWith;
            //            menuControl.imageButton.size
            menuControl.imageButton.layer.cornerRadius = menuControl.imageButton.width/2;
            menuControl.imageButton.clipsToBounds = YES;
            menuControl.imageButton.backgroundColor = STONEOBS_UI_THEME_BACKGROUNDCOLOR;
            if (!model.local_icon_name.length) {
                [menuControl.imageButton sd_setImageWithURL:model.icon.mj_url forState:UIControlStateNormal];
            }
            
            
            menuControl.top = (i / 4) * 100 + 10 ;
            white_view.height = menuControl.bottom + 10;
        }
        top = white_view.bottom + 10;
    });
    
    header.height = top;
    UIView * conten_view = [UIView.alloc initWithFrame:CGRectMake(0, top, UISCREEN_WIDTH, 50)];
    [header addSubview:conten_view];
    conten_view.backgroundColor = UIColor.whiteColor;
    self.seg_contentview = conten_view;
    
    self.segView = [[STTools_SegementAutoView alloc] initWithFrame:CGRectMake(20, 0, UISCREEN_WIDTH * 0.7, 50) andTitle:@[@"精选商品",@"生日大礼包",@"拼团"] handle:^(STTools_SegementAutoView *sender, UIButton *currentSelctedButton) {
        
        [weakSelf.seg_vc.scrollView setContentOffset:CGPointMake(sender.cureentIndex*UISCREEN_WIDTH, 0)];
        THChildSelectViewController * vc = weakSelf.seg_vc.childViewControllers[sender.cureentIndex];
        [vc reload_data_with_selcted_index:sender.cureentIndex];
    }];
    [conten_view addSubview:self.segView];
    
    ({
        STButton * stoneobs_ui_button = [[STButton alloc] initWithFrame:CGRectMake(0, 0, 80, 30)
                                                                  title:@"学校定制"
                                                             titleColor:FlatBlue
                                                              titleFont:15
                                                           cornerRadius:0
                                                        backgroundColor:nil
                                                        backgroundImage:nil
                                                                  image:nil];
        [conten_view addSubview:stoneobs_ui_button];
        stoneobs_ui_button.right = UISCREEN_WIDTH - 15;
        stoneobs_ui_button.centerY = self.segView.centerY;
        stoneobs_ui_button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
        [stoneobs_ui_button setClicAction:^(UIButton *sender) {
            [BFBaseConfigDataController stoneobs_fun_get_customer_service_with_handle:^(NSString * _Nonnull phone, NSString * _Nonnull wechat) {
                NSMutableString *str = [[NSMutableString alloc] initWithFormat:@"telprompt://%@",phone];
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str] options:nil completionHandler:^(BOOL success) {
                    
                }];
            }];
        }];
        
    });
    self.segView.lineSelectedColor = UIColor.clearColor;
    self.segView.lineSelectedView.backgroundColor = UIColor.clearColor;
    self.segView.lineColor = UIColor.clearColor;
    self.segView.autoMoveWithClic = YES;
    
    self.segView.butTitleSelectedColor = UIColor.blackColor;
    self.segView.butTitleColor = STONEOBS_UI_THIRD_TEXT_COLOR;
    self.segView.butTitleFont = [UIFont systemFontOfSize:15];
    self.segView.butTitleSelectedFont = [UIFont fontWithName:STONEOBS_UI_FONT_CU_NAME size:17];
    
    UIImageView * stoneobs_ui_imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 21, 10)];
    stoneobs_ui_imageView.image = [UIImage imageNamed:@"椭圆4"];
    [self.segView.lineSelectedView addSubview:stoneobs_ui_imageView];
    stoneobs_ui_imageView.centerX = self.segView.lineSelectedView.width/2;
    stoneobs_ui_imageView.centerY =  self.segView.lineSelectedView.height / 2;
    self.segView.lineSelectedView.clipsToBounds = NO;
    self.segView.lineSelectedView.top = self.segView.lineSelectedView.top-5;
    self.segView.clipsToBounds = NO;
    
    header.height = conten_view.bottom;
    
    self.tableView.tableHeaderView = header;
}
- (void)stoneobs_ui_config_footer_view{
    THHomeSegeViewController * vc = [THHomeSegeViewController.alloc initWithFrame:CGRectMake(0, 0, UISCREEN_WIDTH, TMUtils.stoneobs_fun_get_tabBarTop - TMUtils.stoneobs_fun_get_navgationBarBootom)];
    self.seg_vc = vc;
    vc.scrollView.delegate = self;
    self.tableView.tableFooterView = vc.view;
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    UIScrollView * current_scrollView = [self.seg_vc current_sub_h_scroll_view];
    if (current_scrollView) {
        if (current_scrollView.contentOffset.y > 0 && scrollView.contentOffset.y < 0) {
            [scrollView setContentOffset:CGPointZero];//如果当前滑动视图滑动偏移大于0，那么tableview 不响应bunce;
        }
    }
    
    if (scrollView == self.tableView) {
        if (self.tableView.contentOffset.y > self.tableView.tableHeaderView.height - 50) {
            [self.view addSubview:self.seg_contentview];
            self.seg_contentview.top = TMUtils.stoneobs_fun_get_navgationBarBootom;
        }else{
            [self.tableView.tableHeaderView addSubview:self.seg_contentview];
            self.seg_contentview.bottom = self.tableView.tableHeaderView.height;
        }
    }else{
        if (scrollView.contentOffset.y < 0) {
            [scrollView setContentOffset:CGPointZero animated:0];
        }
    }
    
    
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    if (scrollView == self.seg_vc.scrollView) {
        NSInteger index = scrollView.contentOffset.x / UISCREEN_WIDTH;
        self.segView.cureentIndex = index;
    }
}
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    if (scrollView == self.seg_vc.scrollView) {
        NSInteger index = scrollView.contentOffset.x / UISCREEN_WIDTH;
        self.segView.cureentIndex = index;
    }
}
#pragma mark --stoneobs Action Method
- (void)stoneobs_action_onselcted_menu_title:(NSString*)title model:(THCateModel*)model{
    if ([model.name isEqualToString:@"秒杀星期六"]) {
        THCateDetailViewController * vc = THCateDetailViewController.new;
        vc.is_xql = YES;
        vc.cate1_id = model.c_id;
        [self pushViewController:vc animated:1];
        
    }else if ([model.name isEqualToString:@"身边育婴师"]) {
        [self pushViewController:THUserBabyHomeViewController.new animated:1];
    }else{
//        THSubCateViewController * vc = THSubCateViewController.new;
//        vc.cate1_id = model.c_id;
//        vc.model = model;
//        [self pushViewController:vc animated:1];
        
        THCategoryHomeViewController * vc = THCategoryHomeViewController.new;
        vc.selected_name = title;
        [self pushViewController:vc animated:1];
    }
    
}
@end
